{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 百度云"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# coding=utf-8\n",
    "\n",
    "import sys\n",
    "import json\n",
    "import base64\n",
    "import time\n",
    "import requests \n",
    "from urllib import request,parse"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_token():\n",
    "    \"\"\"\"\"\"\n",
    "    \n",
    "    API_Key = \"kdCndQjlgSN52SpUMoR0XHrw\"            # 官网获取的API_Key\n",
    "    Secret_Key = \"4Hg2f6yfshDqSu5gVS90O8vEynqgyGcU\" # 为官网获取的Secret_Key\n",
    "    #拼接得到Url\n",
    "    Url = \"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=\"+API_Key+\"&client_secret=\"+Secret_Key\n",
    "    try:\n",
    "        resp = request.urlopen(Url)\n",
    "        result = json.loads(resp.read().decode('utf-8'))\n",
    "        # 打印access_token\n",
    "        print(\"access_token:\",result['access_token'])\n",
    "        return result['access_token']\n",
    "    except request.URLError as err:\n",
    "        print('token http response http code : ' + str(err.code))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "access_token: 24.acc34ce616209078fc9c307f40e24355.2592000.1625981894.282335-24356093\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'24.acc34ce616209078fc9c307f40e24355.2592000.1625981894.282335-24356093'"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "if __name__ == '__main__':\n",
    "    token = get_token()\n",
    "    access_token = token\n",
    "access_token    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "# encoding:utf-8\n",
    "import requests\n",
    "import base64\n",
    "import time\n",
    "def ocr(e):\n",
    "\n",
    "    \n",
    "    request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic\"\n",
    "    # 二进制方式打开图片文件\n",
    "    f = open(e,'rb')\n",
    "    img =base64.b64encode(f.read())\n",
    "    params = {\"image\":img}\n",
    "    # access_token\n",
    "    request_url = request_url + \"?access_token=\" + access_token\n",
    "    headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "    response = requests.post(request_url, data=params, headers=headers)\n",
    "    return response.json()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'error_code': 18, 'error_msg': 'Open api qps request limit reached'}"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ocr('yzm.jpg')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 讯飞"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 网络外链转换base64位编码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [],
   "source": [
    "import base64\n",
    "import requests as req\n",
    "from io import BytesIO\n",
    "\n",
    "def urltobase64(url):\n",
    "    # 图片保存在内存\n",
    "    response = req.get(url)\n",
    "    # 得到图片的base64编码\n",
    "    ls_f=base64.b64encode(BytesIO(response.content).read())\n",
    "    # 将base64编码进行解码\n",
    "    imgdata=base64.b64decode(ls_f)\n",
    "    return imgdata\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {},
   "outputs": [],
   "source": [
    "base64data = urltobase64('https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fs4.sinaimg.cn%2Fmw690%2F003bsgbmgy6R6efoOr1c3&refer=http%3A%2F%2Fs4.sinaimg.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625983371&t=55017fcd05d3eaf413d1d318a5ae08cc')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 调用API"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {},
   "outputs": [],
   "source": [
    "#-*- coding: utf-8 -*-\n",
    "import requests\n",
    "import time\n",
    "import hashlib\n",
    "import base64\n",
    "import json\n",
    "#from urllib import parse\n",
    "# 印刷文字识别 webapi 接口地址\n",
    "URL = \"https://webapi.xfyun.cn/v1/service/v1/ocr/general\"\n",
    "# 应用ID (必须为webapi类型应用，并印刷文字识别服务，参考帖子如何创建一个webapi应用：http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=36481)\n",
    "APPID = \"xxxxx\"\n",
    "# 接口密钥(webapi类型应用开通印刷文字识别服务后，控制台--我的应用---印刷文字识别---服务的apikey)\n",
    "API_KEY = \"xxxxxxxx\"\n",
    "def getOCR(url):\n",
    "#  当前时间戳\n",
    "    curTime = str(int(time.time()))\n",
    "#  支持语言类型和是否开启位置定位(默认否)\n",
    "    param = {\"language\": \"cn|en\", \"location\": \"false\"}\n",
    "    param = json.dumps(param)\n",
    "    paramBase64 = base64.b64encode(param.encode('utf-8'))\n",
    "\n",
    "    m2 = hashlib.md5()\n",
    "    str1 = API_KEY + curTime + str(paramBase64,'utf-8')\n",
    "    m2.update(str1.encode('utf-8'))\n",
    "    checkSum = m2.hexdigest()\n",
    "# 组装http请求头\n",
    "    header = {\n",
    "        'X-CurTime': curTime,\n",
    "        'X-Param': paramBase64,\n",
    "        'X-Appid': APPID,\n",
    "        'X-CheckSum': checkSum,\n",
    "        'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',\n",
    "    }\n",
    "    return header\n",
    "##上传文件并进行base64位编码\n",
    "# with open(r'yzm.jpg', 'rb') as f:\n",
    "#     f1 = f.read()\n",
    "\n",
    "# f1_base64 = str(base64.b64encode(f1), 'utf-8')\n",
    "\n",
    "## 网络外链转换base64位编码\n",
    "\n",
    "f2_base64 = str(base64.b64encode(base64data), 'utf-8')\n",
    "\n",
    "\n",
    "data = {\n",
    "        'image':f2_base64\n",
    "        }\n",
    "\n",
    "\n",
    "r = requests.post(URL, data=data, headers=getHeader())\n",
    "result = str(r.content, 'utf-8')\n",
    "\n",
    "# # 错误码链接：https://www.xfyun.cn/document/error-code (code返回错误码时必看)\n",
    "# print(result)\n",
    "# input(\"Entry the any key to exit\")\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'{\"code\":\"0\",\"data\":{\"block\":[{\"type\":\"text\",\"line\":[{\"confidence\":1,\"word\":[{\"content\":\"7364\"}]}]}]},\"desc\":\"success\",\"sid\":\"wcr001f975e@gza6ea141e50b1463000\"}'"
      ]
     },
     "execution_count": 66,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
